using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Destruction : MonoBehaviour
{
    [SerializeField] float maxHP = 100.0f;
    private float currentHP = 0;
    [Header("失血系数")]
    [SerializeField] float lostHPScale = 5.0f;
    [Header("按递减血量的图片")]
    [SerializeField] Sprite[] sprites;
    private SpriteRenderer spriteRenderer;
    private GameObject prefabBoom;

    void Awake()
    {
        this.spriteRenderer = GetComponent<SpriteRenderer>();
        this.prefabBoom = Resources.Load<GameObject>("Prefabs/Items/Boom");
    }

    void Start()
    {
        this.currentHP = this.maxHP;
    }

    private void OnCollisionEnter2D(Collision2D other)
    {
        var points = other.relativeVelocity.magnitude * this.lostHPScale;
        this.Damage(points);
    }
    
    public void Damage(float points)
    {
        if (this.currentHP <= 0)
            return;

        this.currentHP -= points;
        if (this.currentHP < 0)
        {
            this.currentHP = 0;
        }

        if (this.sprites.Length > 0)
        {
            var index = Mathf.FloorToInt((this.maxHP - this.currentHP) / (this.maxHP / this.sprites.Length));
            if (index >= this.sprites.Length)
            {
                index = this.sprites.Length - 1;
            }
            this.spriteRenderer.sprite = sprites[index];
        }

        if (this.currentHP <= 0)
        {
            Die();
        }
        else
        {
            this.PlayAudioDamage();
        }
    }

    protected virtual void Die()
    {
        Destroy(gameObject);
        Instantiate(this.prefabBoom, transform.position, Quaternion.identity).GetComponent<Boom>().Show();
        this.PlayAudioDestroy();
    }

    protected virtual void PlayAudioDamage()
    {
        AudioManager.Instance.PlayWoodDamage(transform.position, 0.5f);
    }
    
    protected virtual void PlayAudioDestroy()
    {
        AudioManager.Instance.PlayWoodDestroy(transform.position, 0.2f);
    }
}
